package com.helloandroid.ads

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import com.anythink.core.api.ATAdConst
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.nativead.api.*
import com.anythink.network.gdt.GDTATConst
import com.anythink.network.toutiao.TTATConst
import com.business.TDKeys
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.MyLog
import com.qq.e.ads.nativ.ADSize
import com.helloandroid.ads.NativeDemoRender

object NativeAdUtil {

    var adNative: ATNative? = null

    private var nativeListener = object : ATNativeNetworkListener {
        override fun onNativeAdLoaded() {
            MyLog.info("onNativeAdLoaded called!")
        }

        override fun onNativeAdLoadFail(adError: AdError?) {
            //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
            //AdError，请参考 https://docs.toponad.com/#/zh-cn/android/android_doc/android_test?id=aderror
            MyLog.info("onNativeAdLoadFail: ${adError?.fullErrorInfo}");
        }
    }

    fun initNativeAd() {
        if (adNative == null) {
            adNative = ATNative(MyApplication.app.applicationContext, TDKeys.TopOnNativePlacementId, nativeListener)
            loadNativeAd()

            MyLog.info("TDKeys.TopOnNativePlacementId:${TDKeys.TopOnNativePlacementId}")
        }
    }

    fun loadNativeAd() {
        adNative?.let {
            val ctx = MyApplication.app.applicationContext
            val padding = ctx.resources.getDimension(R.dimen.dp10)
            val adViewWidth = ctx.resources.displayMetrics.widthPixels - 2 * padding

            val paddingUpDown = ctx.resources.getDimension(R.dimen.dp30)
            val adViewHeight = ctx.resources.getDimension(R.dimen.dp340) - 2 * paddingUpDown

            MyLog.elog("adViewWidth:$adViewWidth,adViewHeight:$adViewHeight")
            val localMap: MutableMap<String, Any> = HashMap()

            localMap[ATAdConst.KEY.AD_WIDTH] = adViewWidth.toInt()
            localMap[ATAdConst.KEY.AD_HEIGHT] = adViewHeight.toInt()

            //穿山甲（Pangle）
            localMap[TTATConst.NATIVE_AD_IMAGE_HEIGHT] = 0;

            //腾讯广告（Tencent Ads），ADSize.AUTO_HEIGHT值为-2
            localMap[GDTATConst.AD_HEIGHT] = ADSize.AUTO_HEIGHT;

            it.setLocalExtra(localMap)
            it.makeAdRequest()
        }
    }


    @JvmStatic
    fun showNativeAd(activity: Activity, adView: ATNativeAdView) {

        if (!AppConfig.AdToggle || AppConfig.isFake){
            return
        }

        adNative?.let {
            val ad = it.nativeAd
            if (ad != null) {
                adView.visibility = View.VISIBLE
                MyLog.elog("nativeAd== is not null! show it !")
                ad.setNativeEventListener(adListener)
                ad.setDislikeCallbackListener(dislikeListener)
                val render = NativeDemoRender(activity)
                ad.renderAdView(adView, render)
                ad.prepare(adView, render.clickView, null)
            } else {
                adView.visibility = View.GONE
                MyLog.elog("nativeAd== is Null! reload!")
                loadNativeAd()
            }
        }
    }

    var dislikeListener = object : ATNativeDislikeListener() {
        override fun onAdCloseButtonClick(view: ATNativeAdView?, p1: ATAdInfo?) {
            view?.let {
                if (it.parent != null) {
                    val parentView = it.parent as ViewGroup
                    parentView.removeView(view)
                }
            }
        }
    }
    var adListener = object : ATNativeEventListener {
        override fun onAdImpressed(p0: ATNativeAdView?, atAdInfo: ATAdInfo?) {
            MyLog.elog("native ad onAdImpressed:${atAdInfo}");
            loadNativeAd()
        }

        override fun onAdClicked(p0: ATNativeAdView?, atAdInfo: ATAdInfo?) {
            MyLog.elog("native ad onAdClicked:${atAdInfo}");
        }

        override fun onAdVideoStart(p0: ATNativeAdView?) {
        }

        override fun onAdVideoEnd(p0: ATNativeAdView?) {
        }

        override fun onAdVideoProgress(p0: ATNativeAdView?, p1: Int) {
        }

    }

//    fun getView(activity: Activity):ATNativeAdView{
//        if (anyThinkNativeAdView != null){
//            return  anyThinkNativeAdView!!
//        }
//        anyThinkNativeAdView = ATNativeAdView(activity)
//        return anyThinkNativeAdView!!
//    }
}